Page({
  data: {
    messages: [],
    inputMsg: '',
    wsStatus: false
  },

  onLoad() {
    this.connectWS()
  },

  // 连接WebSocket
  connectWS() {
    const ws = wx.connectSocket({
      url: 'ws://localhost:3002/chat'
    })

    ws.onOpen(() => {
      this.setData({ wsStatus: true })
      console.log('WebSocket连接成功')
    })

    ws.onMessage((res) => {
      const response = JSON.parse(res.data)
      this.pushMessage({
        content: response.content,
        role: 'assistant',
        timestamp: Date.now()
      })
    })

    ws.onClose(() => {
      this.setData({ wsStatus: false })
      console.log('WebSocket已断开')
    })

    this.ws = ws
  },

  // 输入消息
  handleInput(e) {
    this.setData({ inputMsg: e.detail.value })
  },

  // 发送消息
  sendMessage() {
    const msg = this.data.inputMsg.trim()
    if (!msg || !this.data.wsStatus) return

    this.pushMessage({
      content: msg,
      role: 'user',
      timestamp: Date.now()
    })

    this.ws.send({
      data: JSON.stringify({
        content: msg,
        session_id: Date.now().toString()
      }),
      success: () => this.setData({ inputMsg: '' })
    })
  },

  // 添加消息到列表
  pushMessage(message) {
    this.setData({
      messages: [...this.data.messages, message]
    })
  }
})

Page({
  data: {
    messages: [],
    inputMsg: '',
    wsStatus: false,
    heartbeatInterval: null
  },

  onLoad() {
    this.connectWS()
  },

  onUnload() {
    this.disconnectWS()
  },

  // 连接WebSocket
  connectWS() {
    if (this.ws && this.data.wsStatus) {
      console.log('WebSocket 已经连接');
      return;
    }

    const ws = wx.connectSocket({
      url: 'ws://localhost:3002/chat'
    })

    ws.onOpen(() => {
      this.setData({ wsStatus: true })
      console.log('WebSocket连接成功')
      this.startHeartbeat()
    })

    ws.onError((error) => {
      console.error('WebSocket连接失败', error)
      this.setData({ wsStatus: false })
    })

    ws.onMessage((res) => {
      try {
        const response = JSON.parse(res.data)
        this.pushMessage({
          content: response.content,
          role: 'assistant',
          timestamp: Date.now()
        })
      } catch (e) {
        console.error('解析消息失败', e)
      }
    })

    ws.onClose(() => {
      this.setData({ wsStatus: false })
      console.log('WebSocket已断开')
      this.stopHeartbeat()
    })

    this.ws = ws
  },

  // 断开WebSocket连接
  disconnectWS() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
      this.setData({ wsStatus: false })
      this.stopHeartbeat()
    }
  },

  // 启动心跳机制
  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.ws && this.data.wsStatus) {
        this.ws.send({
          data: JSON.stringify({ type: 'heartbeat' }),
          success: () => console.log('心跳发送成功'),
          fail: (error) => console.error('心跳发送失败', error)
        })
      }
    }, 30000) // 每30秒发送一次心跳
  },

  // 停止心跳机制
  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  },

  // 输入消息
  handleInput(e) {
    this.setData({ inputMsg: e.detail.value })
  },

  // 发送消息
  sendMessage() {
    const msg = this.data.inputMsg.trim()
    if (!msg || !this.data.wsStatus) return

    this.pushMessage({
      content: msg,
      role: 'user',
      timestamp: Date.now()
    })

    this.ws.send({
      data: JSON.stringify({
        content: msg,
        session_id: Date.now().toString()
      }),
      success: () => this.setData({ inputMsg: '' }),
      fail: (error) => {
        console.error('消息发送失败', error)
        this.pushMessage({
          content: '消息发送失败，请重试',
          role: 'system',
          timestamp: Date.now()
        })
      }
    })
  },

  // 添加消息到列表
  pushMessage(message) {
    this.setData({
      messages: [...this.data.messages, message]
    })
  }
})